# -*- coding: utf-8 -*-
import codecs
import xdrlib ,sys
import xlrd
import os
import os.path

reload(sys)
sys.setdefaultencoding('utf-8')

def open_excel(file):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception,e:
        print str(e)

#分割字符串内容
def split_colcontent(_str):
	if None == _str:
		return None
	return _str.split("#")

# 获取当前表的主键列索引
def GetCurrentTablePrimaryKey(_table, row):
	result = ""
	for col in range(0, _table.ncols):
		field = _table.cell(1, col).value
		if (None != field and "main" in field):
			primaryKey = (_table.cell(row, col).value)
			if( "" == result.strip()):
				result += str(primaryKey)
			else:
				result += "_"+str(primaryKey)
	if("" == result):
		no_primary_key = "%s表缺少主键,生成失败" % _table.name
		print(no_primary_key.decode('utf-8'))
	return result

# 根据行和列，获取一个具体的数值，会根据type进行转换
def GetCurrentTableValue(table, row, col):
	if(None == table or row < 0 or col < 0):
		return None
	pass

	#首先获取到类型
	field_type = table.cell(2, col).value

	# 获取内容
	field_value = table.cell(row, col).value

	if(field_type == "int"):
		return int(field_value)
	elif(field_type == "string"):
		return str("[[ %s]]" % field_value)
	elif(field_type == "float"):
		return float(field_value)
	elif(field_type == "long"):
		return long(field_value)
	else:
		return None


def readxls(file, clientdir, serverdir):
	data = open_excel(file)
	try:
		namearr = data.sheet_names()
		pass
	except Exception, e:
		message = "Fail:请保存所有配置表并且关闭后再执行"
		print(message.decode('utf-8'))
		return

	for shindex in range(0,2):
		namesplit = namearr[shindex].split('.')
		if(namesplit[0]=="c"):
			outputdir = clientdir
		elif(namesplit[0]=="s"):
			outputdir = serverdir
		else:
			return 

		#print(outputdir+namesplit[1]+".lua")
		table = data.sheets()[shindex]
		outputPath = "%s/AppSet_%s.lua" % (outputdir, namesplit[1])
		output = codecs.open(outputPath, "w", "utf-8")

		# 组装内容
		output.write("\n--由xls2lua自动生成，不需要手动修改\n")
		output.write("\nAppSet_%s = {\n\n" % (namesplit[1]))

		#获取当前表的主键
		for row in range(3, table.nrows):
			#tmp = "\t["+str(table.cell(row, 0).value)+"] = {  "
			primaryKey = GetCurrentTablePrimaryKey(table, row)
			if("" == primaryKey):
				return
			tmp = "\t[\"%s\"] = " % primaryKey
			tmp += "{  "
			for col in range(0, table.ncols):
				# cchar = str(table.cell(row, col).value)
				field_value = GetCurrentTableValue(table, row, col)
				if(None != field_value):
					cchar = str(field_value)
					tmp += str(table.cell(1, col).value) + " = " + cchar.decode('utf-8') + ", "
			# 写入col组合内容
			output.write(tmp)
			# 写入parse data 部分
			output.write("parse_data = {}")
			# 写入｝
			output.write("},\n")

			#output.write(tmp+"parse_data = {},}, \n")
		output.write("\n}\n")
		output.write("\nreturn AppSet_%s" % (namesplit[1]))
		# 组装结束

		output.close()

		# 打印
		print("succes : %s out put path : " % outputdir+namesplit[1]+".lua" )

def makeconfig(rootdir, cdir, sdir):
	if (os.path.exists(cdir)==False):
		os.makedirs(cdir)
	if (os.path.exists(sdir)==False):
		os.makedirs(sdir)
	for parent,dirnames,filenames in os.walk(rootdir):     
		for dirname in  dirnames:
			makeconfig(rootdir+dirname, cdir+dirname+"/", sdir+dirname+"/")
		for filename in filenames:                         
			if (filename[0] != ".") and (parent == rootdir):
				# print(os.path.join(parent,filename).split(rootdir)[1])
				readxls(os.path.join(parent,filename), cdir, sdir)

if __name__=="__main__":
	makeconfig("desgin/", "client/", "server/")


